"""
@author: 江同学呀
@file: base_index.py
@date: 2024/2/9 0:12
@desc: 
"""
from typing import Optional, List, Union, Type, Dict

from espc.orm.model.index_module.index_setting import IndexSetting
from espc.orm.model.model.base_document import BaseDocument
from espc.orm.model.model.base_alias import BaseAlias


class BaseIndex:
    """
    索引基类

    - index_name: 索引名称
    - alias: 别名
    - document: 文档模型
    """
    _instance = None

    index_name: str = ""
    _name: str = index_name
    alias: Optional[Union[BaseAlias, List[BaseAlias], Type[BaseAlias], List[Type[BaseAlias]], str, List[str]]] = None
    # todo 优化settings的逻辑
    settings: Union[IndexSetting, Dict] = {}
    document: Optional[BaseDocument] = None
    # todo 增加properties的逻辑

    def __init__(
            self,
            index_name: str,
            alias: Union[BaseAlias, List[BaseAlias], Type[BaseAlias], List[Type[BaseAlias]], str, List[str]] = None,
            document: Optional[BaseDocument] = None
    ):
        self.index_name: str = index_name
        self.alias: Optional[Union[BaseAlias, List[BaseAlias]]] = alias
        self.document: Optional[BaseDocument] = document
        return

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super().__new__(cls)
        return cls._instance

    def __str__(self):
        return self.index_name

    def __repr__(self):
        return (
            f"<{self.__class__.__name__} "
            f"index_name={self.index_name}, alias={self.alias}, document={self.document} "
            f"object at {id(self)}>"
        )

    def __init_subclass__(cls, **kwargs):
        """
        子类被声明完时调用
        :param kwargs:
        :return:
        """
        # cls._core._ref_field_name(model=cls)
        # cls._core._add_index(index=cls.index, model=cls)
        cls._name = cls.index_name
        return

    @classmethod
    def _build(cls):
        """
        构建索引结构体
        :return:
        """
        body: Dict = {}
        if cls.document:
            body["mappings"] = {
                "properties": cls.document._build()
            }
        if cls.settings:
            body["settings"] = cls.settings._build() if isinstance(cls.settings, IndexSetting) else cls.settings or {}
        return body


